from PyQt5 import QtWidgets
from EasyDailyReporterUi import Ui_Form
import sys
import os
import win32com.client as win32
from datetime import datetime
import time
from PyQt5.QtCore import *
#from PyQt5.QtGui import *

class Easydr(QtWidgets.QWidget,Ui_Form):
    def __init__(self,daily_dir='',remind_H=0,remind_M=0,send_time='',to='',subject=''):
        super(Easydr,self).__init__()
        
        self.setupUi(self)
        self.daily_dir = daily_dir
        self.remind_H,self.remind_M = remind_H,remind_M
        self.send_time = send_time
        self.to = to
        self.subject = subject
        
        self.Setting()

        self.pushButton_open.clicked.connect(self.Open)
        self.pushButton_send.clicked.connect(self.Send)
        self.timer = QTimer(self)
        self.timer.timeout.connect(self.Remind)
        self.timer.start(3000)

    def Setting(self):
        self.lineEdit_dir.setText(self.daily_dir)
        self.timeEdit_remind.setTime(QTime(self.remind_H,self.remind_M,0))
        self.lineEdit_sendtime.setText(self.send_time)
        self.mail_to.setText(self.to)
        mail_date = datetime.now().strftime('%Y%m%d')
        self.mail_subject.setText(mail_date + self.subject)
    

    def Open(self):
        file_dir = self.lineEdit_dir.text()
        command = "start"+" "+file_dir
        open_result = os.system(command)
        if open_result:
            QtWidgets.QMessageBox.information(self,'Warning:',"请确认该文件:%s 是否已打开或文件不纯在"%file_dir)
            return
        
    def Send(self):
        mail_to = self.mail_to.text()
        mail_subject = self.mail_subject.text()
        file_dir = self.lineEdit_dir.text()

        outlook = win32.Dispatch('outlook.application')
        mail = outlook.CreateItem(0)
        mail.To = mail_to
        mail.Subject = mail_subject
        mail.Attachments.Add(file_dir)

        mail.Send()
        
    def Remind(self):
    #check remind time
        nowtime = datetime.now().strftime('%H:%M')
        remindtime = self.timeEdit_remind.text()
        sendtime = self.lineEdit_sendtime.text()
        if nowtime == remindtime:
            self.Open()
            time.sleep(60)
        if nowtime == sendtime:
            self.Send()
            time.sleep(60)
            
if __name__ == "__main__":
    #setting
    daily_dir = "E:\\PMC_WORK\\PMCDailyReport\\DailyReport.xlsx"
    remind_H = 16
    remind_M = 30
    send_time = '17:00'
    to = 'ruru_liao@tianma.cn'
    subject = '日报'
    
    app = QtWidgets.QApplication(sys.argv)
    window = Easydr(daily_dir,remind_H,remind_M,send_time,to,subject)
    window.show()
    sys.exit(app.exec())
    
